package com.ruoyi.service.impl;

import com.camp.domain.CUser;
import com.camp.service.ICUserService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;

import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.core.WxCore;
import com.ruoyi.dmain.WxLoginUser;
import com.ruoyi.framework.web.service.SysPermissionService;

import com.ruoyi.service.IWxLoginService;
import com.ruoyi.system.service.ISysUserService;


import com.ruoyi.util.ThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.ruoyi.framework.web.service.TokenService;

import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Random;

/**
 * 微信登录服务实现
 * @auth zhaoly
 * @date 2024-01-25 10:24
 */
@Service
public class WxLoginService implements IWxLoginService {

        @Value("${wechart.userType}")
    private String userType;

    @Autowired
    private WxCore core;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ICUserService icUserService;


    /**
     * 微信登录
     * @param code 小程序预登录coce
     * @param userName 学号/工号/手机号
     * @param password 登录密码
     * @return 登录用户
     */
    @Override
    public WxLoginUser login(@RequestParam(name = "avatarUrl") String imgurl, String code, String userName, String password){

        //请求wx后台通过code请求openid
        String openid = core.getOpenId(code);
        //获取不到openid直接返回
        if(StringUtils.isBlank(openid)){
            return new WxLoginUser("","","", -1, "获取openid失败");
        }

        //通过openid查询系统用户
        SysUser sysUser = userService.getUserByOpenid(openid);
        if(sysUser != null){
            return generatorLoginUser(sysUser);
        }else {
            String id =null;
            UUID uuid = UUID.randomUUID();
            id = uuid.toString();

            //去掉随机ID的短横线
            id = id.replace("-", "");

            //将随机ID换成数字
            int num = id.hashCode();
            //去绝对值
            num = num < 0 ? -num : num;

            id = String.valueOf(num);
            Random rand = new Random();
            int number = rand.nextInt(1000)+100;
            CUser cUser =new CUser();
            cUser.setUsername("luying:"+number);
            cUser.setOpenid(openid);
            cUser.setPassword("123456");
            cUser.setImg(imgurl);
            cUser.setUserId(id);

            icUserService.insertCUser(cUser);
            SysUser sysUser01=new SysUser();
            sysUser01.setUserName(cUser.getUsername());
            sysUser01.setPassword(cUser.getPassword());
            sysUser01.setAvatar(cUser.getImg());
            sysUser01.setOpenid(cUser.getOpenid());
            sysUser01.setStatus("0");
            //nickName就是用户的id
            sysUser01.setNickName(cUser.getUserId());
            userService.insertUser(sysUser01);
//            threadLocal.set(cUser.getUserId());
            ThreadLocalUtil.set(cUser.getUserId());
            System.out.println("22222222233333333333333");
            System.out.println(ThreadLocalUtil.get());
            return new WxLoginUser(cUser.getUserId(),cUser.getImg(),cUser.getUsername(), 0, "登录成功并注册成功");
        }

//        //通过用户名密码查询系统用户
//        sysUser = userService.getUserByName(userName);
//        if(sysUser != null){
//            if(SecurityUtils.matchesPassword(password, sysUser.getPassword())){
//                sysUser.setWxOpenid(openid);
//                userService.updateUser(sysUser);
//                return generatorLoginUser(sysUser);
//            }else{
//                return new WxLoginUser(sysUser.getNickName(), sysUser.getDept().getDeptName(), -1, "用户名或密码不正确");
//            }
//        }else{
//
//            //通过openid查询已注册未审核用户
//            CUser registerUser = icUserService.getUserByOpenid(openid);
//            if(registerUser != null){
//                return generatorLoginUser(registerUser);
//            }
//
//            //通过用户名密码查询已注册未审核用户
//            registerUser = icUserService.getUserByName(userName);
//            if(registerUser != null){
//                if(SecurityUtils.matchesPassword(password, registerUser.getPassword())){
//                    registerUser.setOpenid(openid);
//                    icUserService.updateSysRegzhuce(registerUser);
//                    return generatorLoginUser(registerUser);
//                }else{
//                    return new WxLoginUser(registerUser.getName(), registerUser.getDept(), -1, "用户名或密码不正确");
//                }
//            }
//        }

    }



    /**
     * 生成微信用户登录参数
     * @param user 系统用户
     * @return
     */
    private WxLoginUser generatorLoginUser(SysUser user){
        if(user.getStatus().equals("1")){
            return new WxLoginUser("","","",  3, "该账号已被停用");
        }else{
            LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
            String token = tokenService.createToken(loginUser);
            return new WxLoginUser(user.getNickName(),user.getAvatar(),user.getUserName(),0,"");
        }
    }

    /**
     * 生成微信用户登录参数
     * @param user 申请注册用户
     * @return
     */
    private WxLoginUser generatorLoginUser(CUser user){

        return new WxLoginUser("","", "", -1, "用户名或密码不正确");
    }

//    /**
//     * 新用户注册
//     *
//     * @param user 新注册用户实例
//     * @return 注册结果
//     */
//    @Override
//    public int register(SysRegzhuce user) {
//        user.setCreateTime(DateUtils.getNowDate());
//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
//        user.setStatus(0);
//        user.setCreateBy("1");
//        user.setUpdateBy("1");
//        return sysRegzhuceService.insertSysRegzhuce(user);
//    }
}